#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：member_svc.py.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/7/18 下午4:49 
@explain : 
"""
import math
from datetime import datetime, timedelta

from fastapi import Request
from sqlalchemy import text, null

from app import utils, dao
from app.dao import XlxMemberActionLog, XlxMember, XlxCompany, XlxResume, XlxMemberBind


class MemberService:
    @classmethod
    def get_login_log(cls, uid: int = 0, page: int = 1, pagesize: int = 10,
                      request: Request = None) -> utils.HttpResponse:
        where = {'is_login': 1}
        if uid > 0:
            where['uid'] = uid
        total, result = dao.MemberQueryDao.find_member_action_log_list(page=page, page_size=pagesize, **where)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        map_platform = {
            'app': 'APP',
            'mobile': '手机浏览器',
            'wechat': '微信浏览器',
            'miniprogram': '微信小程序',
            'tiktok': '抖音小程序',
            'web': '电脑浏览器',
            'system': '系统',
        }
        for value in result:
            temp = {'id': value.id,
                    'utype': value.utype,
                    'uid': value.uid,
                    'content': value.content,
                    'addtime': utils.StringUtil.format_timestamp_to_str(value.addtime),
                    'ip': value.ip, 'ip_addr': value.ip_addr,
                    'platform_cn': map_platform[value.platform] if value.platform in map_platform else '-',
                    'is_login': value.is_login}
            records_list.append(temp)
        res = {'items': records_list, 'total': total, 'current_page': page, 'pagesize': pagesize,
               'total_page': math.ceil(total / pagesize)}
        return utils.ResponseSuccess(res)

    @classmethod
    def get_action_log(cls, utype: int = 0, uid: int = 0, keyword: str = '', page: int = 1, pagesize: int = 10,
                       request: Request = None) -> utils.HttpResponse:
        where_clause = []
        if uid > 0:
            where_clause.append(XlxMemberActionLog.uid == uid)
        if utype > 0:
            where_clause.append(XlxMemberActionLog.utype == utype)
        fulltext_clause = None
        if keyword:
            fulltext_keywords = ' '.join(['+' + word for word in keyword.split() if word])
            fulltext_clause = text("MATCH(content) AGAINST(:keyword IN BOOLEAN MODE)").bindparams(
                keyword=fulltext_keywords)

        total, result = dao.MemberQueryDao.find_member_actionlog_list(utype=utype, where_clause=where_clause,
                                                                      fulltext_clause=fulltext_clause, page=page,
                                                                      page_size=pagesize)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        map_platform = {
            'app': 'APP',
            'mobile': '手机浏览器',
            'wechat': '微信浏览器',
            'miniprogram': '微信小程序',
            'tiktok': '抖音小程序',
            'web': '电脑浏览器',
            'system': '系统',
        }
        for value in result:
            temp = {'id': value.id,
                    'utype': value.utype,
                    'uid': value.uid,
                    'content': value.content,
                    'companyname': value.companyname,
                    'fullname': value.fullname,
                    'addtime': utils.StringUtil.format_timestamp_to_str(value.addtime),
                    'ip': value.ip, 'ip_addr': value.ip_addr,
                    'platform_cn': map_platform[value.platform] if value.platform in map_platform else '-',
                    'is_login': value.is_login}
            records_list.append(temp)
        res = {'items': records_list, 'total': total, 'current_page': page, 'pagesize': pagesize,
               'total_page': math.ceil(total / pagesize)}
        return utils.ResponseSuccess(res)

    @classmethod
    def index(cls, list_type: str = None, key_type: int = 0, keyword: str = None, status: str = None, sort: str = None,
              regtime: str = None, platform: str = None, utype: int = 0, is_openid: int = 0, is_email: int = 0,
              page: int = 1, pagesize: int = 10,
              request: Request = None) -> utils.HttpResponse:
        map_platform = {
            'app': 'APP',
            'mobile': '手机浏览器',
            'wechat': '微信浏览器',
            'miniprogram': '微信小程序',
            'tiktok': '抖音小程序',
            'web': '电脑浏览器',
            'system': '系统',
        }
        where_clause = []
        company_where_clause = []
        personal_where_clause = []
        member_bind_where_clause = []
        if key_type and keyword:
            if key_type == 1:
                where_clause.append(XlxMember.uid == keyword)
            elif key_type == 2:
                where_clause.append(XlxMember.username.like('%' + keyword + '%'))
            elif key_type == 3:
                where_clause.append(XlxMember.mobile.like('%' + keyword + '%'))
            elif key_type == 4:
                if list_type == 'company':
                    company_where_clause.append(XlxCompany.companyname.like('%' + keyword + '%'))
                elif list_type == 'personal':
                    personal_where_clause.append(XlxResume.fullname.like('%' + keyword + '%'))
        if status:
            where_clause.append(XlxMember.status == int(status))

        if regtime:
            days_to_subtract = int(regtime)
            cut_date = datetime.now() - timedelta(days=days_to_subtract)
            cut_date_timestamp = int(cut_date.timestamp())
            where_clause.append(XlxMember.reg_time >= cut_date_timestamp)
        if platform:
            where_clause.append(XlxMember.platform == platform)

        if sort:
            sort_by = 'last_login_time'
        else:
            sort_by = 'uid'
        if utype > 0:
            where_clause.append(XlxMember.utype == utype)
        if is_openid == 1:
            member_bind_where_clause.append(XlxMemberBind.id.isnot(null()))
        elif is_openid == 2:
            member_bind_where_clause.append(XlxMemberBind.id.is_(null()))

        if is_email == 1:
            where_clause.append(XlxMember.email != '')
        elif is_email == 2:
            where_clause.append(XlxMember.email == '')

        total, result = dao.MemberQueryDao.member_list(list_type, where_clause=where_clause,
                                                       company_where_clause=company_where_clause,
                                                       personal_where_clause=personal_where_clause,
                                                       member_bind_where_clause=member_bind_where_clause,
                                                       sort_by=sort_by, page=page, page_size=pagesize)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        for value in result:
            temp = {'avatar': value.avatar,
                    'disable_im': value.disable_im,
                    'display': True if value.status == 1 else False,
                    'email': value.email,
                    'is_openid': '否' if value.openid == '' else '是',
                    'last_login_address': value.last_login_address,
                    'last_login_ip': value.last_login_ip,
                    'last_login_time': utils.StringUtil.format_timestamp_to_str(value.last_login_time),
                    'mobile': value.mobile,
                    'openid': value.openid,
                    'platform': value.platform,
                    'platform_cn': map_platform[value.platform] if value.platform in map_platform else '未知平台',
                    'reg_address': value.reg_address,
                    'reg_time': utils.StringUtil.format_timestamp_to_str(value.reg_time),
                    'reg_ip': value.reg_ip,
                    'robot': value.robot,
                    'status': value.status,
                    'uid': value.uid,
                    'username': value.username,
                    'utype': value.utype,
                    }
            if list_type == 'company':
                temp['companyname'] = value.companyname
            records_list.append(temp)
        res = {'items': records_list, 'total': total, 'current_page': page, 'pagesize': pagesize,
               'total_page': math.ceil(total / pagesize)}
        return utils.ResponseSuccess(res)
